package com.ellison.zookeeperdemo.lock2;

import java.util.concurrent.CountDownLatch;

/**
 * 分布式锁   非独占锁实现
 * watch订阅前一节点，形成链式 订阅，提高效率
 *
 * @Author Ellison Pei
 * @Date 2021/6/30 21:15
 **/
public class OrderServiceImproveLock implements Runnable {

    private OrderNumFactory orderNumFactory = new OrderNumFactory();
    private static Integer count = 50;
    private static CountDownLatch cdl = new CountDownLatch(count);

    private Lock lock = new ZkImpLockImpl();

    @Override
    public void run() {
        try {
            // 先等待
            cdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            createOrderNum();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void createOrderNum() {
        lock.lock();
        String orderNum = orderNumFactory.createOrderNum();
        System.out.println(Thread.currentThread().getName() + "创建了订单号：【" + orderNum + "】");
        lock.unlock();
    }

    public static void main(String[] args) {
        for (int i = 0; i < count; i++) {
            new Thread(new OrderServiceImproveLock()).start();
            cdl.countDown();
        }
    }
}
